from tkinter import *
from tkinter import filedialog
import os
from tkinter.messagebox import showinfo
from collections import Counter

class statistics():
    def __init__(self):
        self.root=Tk()
        self.root.title('Select and Statistics')
        self.root.geometry('480x480')  # 这里的乘号不是 * ，而是小写英文字母 x
        self.button_select=Button()
        self.button_confirm=Button()
        self.text_path=Text()
        self.filelist=[]
        self.result_list=Listbox()
        self.k=10
    def addFunction(self):
        self.button_select=Button(self.root, text='选取文件夹', command=self.selectfile)
        self.button_select.place(relx=0.1, rely=0.03, relwidth=0.2, relheight=0.05)
        #self.button_select.pack()
        self.button_confirm=Button(self.root,text='开始提取',command=self.selectkey)
        self.button_confirm.place(relx=0.7, rely=0.1, relwidth=0.2, relheight=0.05)
        #self.button_confirm.pack()
        self.text_path=Entry(self.root)
        self.text_path.place(relx=0.32,rely=0.03,relwidth=0.6,relheight=0.05)
        self.label=Label(self.root,text="设置topk中的k(默认10):")
        self.label.place(relx=0.05, rely=0.1, relwidth=0.35, relheight=0.05)
        self.topk = Entry(self.root)
        self.topk.place(relx=0.42, rely=0.1, relwidth=0.2, relheight=0.05)
        #self.text_path.pack()
        self.result_list=Listbox(self.root)
        self.result_list.place(relx=0.1,rely=0.17,relwidth=0.8,relheight=0.8)
    def selectfile(self):
        root = Tk()
        root.withdraw()
        self.Folderpath = filedialog.askdirectory()
        print('Folderpath:', self.Folderpath)
        self.text_path.delete(0, "end")
        self.text_path.insert(0, self.Folderpath)
        self.filelist.clear()
        for filename in os.listdir(self.Folderpath):
            if os.path.splitext(filename)[1] == '.txt':
                self.filelist.append(os.path.join(self.Folderpath,filename))

    def selectkey(self):
        #YR A1 AD JF K1
        lis=["提取年份...","提取作者...","提取机构...","提取Top10期刊...","提取Top10关键词...","提取完成！"]
        year=[]
        writer=[]
        agent=[]
        article=[]
        keyword=[]
        if self.topk.get()!="":
            self.k=int(self.topk.get())
        if len(self.filelist)==0:
            showinfo(title='消息提示框', message='当前路径下不存在txt文件！')
        else:
            for file in self.filelist:
                with open(file, encoding='utf-8') as f:
                    for line in f:
                        if len(line.strip().split(" ")) <= 1:
                            continue
                        if line.strip().split(" ")[0]=="YR":
                            year.append(line.strip().split(" ")[1])
                        elif line.strip().split(" ")[0]=="A1":
                            writer+=line.strip().split(" ")[1].split(";")[:-1]
                        elif line.strip().split(" ")[0]=="AD":
                            agent+=line.strip().split(" ")[1].split(";")[:-1]
                        elif line.strip().split(" ")[0]=="JF":
                            article.append(line.strip().split(" ")[1])
                        elif line.strip().split(" ")[0] == "K1":
                            keyword += line.strip().split(" ")[1].split(";")
            ac_year = Counter(year)
            ac_writer=Counter(writer)
            ac_agent=Counter(agent)
            ac_article=Counter(article)
            ac_keyword=Counter(keyword)
            if not os.path.exists(os.path.join(self.Folderpath,"result")):
                os.mkdir(os.path.join(self.Folderpath,"result"))
            with open(os.path.join(self.Folderpath,'result',"year.txt"), 'w+',encoding='utf-8') as fout:
                for item in ac_year.most_common(len(ac_year)):
                    fout.write(item[0] +": "+str(item[1])+'\n')
                fout.close()
                self.result_list.insert(0,lis[0])
            with open(os.path.join(self.Folderpath,'result',"writer.txt"), 'w+',encoding='utf-8') as fout:
                for item in ac_writer.most_common(len(ac_writer)):
                    fout.write(item[0] +": "+str(item[1])+'\n')
                fout.close()
                self.result_list.insert(1,lis[1])
            with open(os.path.join(self.Folderpath,'result',"agent.txt"), 'w+',encoding='utf-8') as fout:
                for item in ac_agent.most_common(len(ac_agent)):
                    fout.write(item[0] +": "+str(item[1])+'\n')
                fout.close()
                self.result_list.insert(2,lis[2])
            with open(os.path.join(self.Folderpath,'result',"article.txt"), 'w+',encoding='utf-8') as fout:
                for item in ac_article.most_common(self.k):
                    fout.write(item[0] +": "+str(item[1])+'\n')
                fout.close()
                self.result_list.insert(3,lis[3])
            with open(os.path.join(self.Folderpath,'result',"key_words.txt"), 'w+',encoding='utf-8') as fout:
                for item in ac_keyword.most_common(self.k):
                    fout.write(item[0] +": "+str(item[1])+'\n')
                fout.close()
                self.result_list.insert(4,lis[4])
            self.result_list.insert(5,"提取结果保存至"+os.path.join(self.Folderpath,"results"))


    def run(self):
        self.root.mainloop()

if __name__ == '__main__':
    s=statistics()
    s.addFunction()
    s.run()